package com.hisense.settings;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.os.Handler;
import android.view.KeyEvent;
import java.io.IOException;
import android.view.WindowManager;
import com.android.settings.R;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.view.IWindowManager;
import android.os.SystemClock;
import android.os.RemoteException;
import android.view.InputDevice; 
import android.os.ServiceManager;
import android.os.PowerManager;
import android.content.SharedPreferences;

public class CountDownService extends Service{

	private static String TAG="CountDownService";

	private static final int    MSG_SET_SLEEP_TIMER = 1;
	private static final int    MSG_COUNT_DOWN_1S = 2;
	private static AlertDialog        localDialog = null;

	private static final int    SLEEP_TIMER_10MIN = 10*60*1000;
	private static final int    SLEEP_TIMER_20MIN = 20*60*1000;
	private static final int    SLEEP_TIMER_30MIN = 30*60*1000;
	private static final int    SLEEP_TIMER_40MIN = 40*60*1000;
	private static final int    SLEEP_TIMER_50MIN = 50*60*1000;
	private static final int    SLEEP_TIMER_60MIN = 60*60*1000;
	private static final int    SLEEP_TIMER_90MIN = 90*60*1000;
	private static final int    SLEEP_TIMER_120MIN = 120*60*1000;

	private static int iCount = 60;
	SharedPreferences.Editor editor;
	
	private Handler  mHandler = new Handler()
                              {
                                  public void handleMessage(
                                          android.os.Message msg)
                                  {
                                      super.handleMessage(msg);
                                      if (msg.what == MSG_SET_SLEEP_TIMER)
                                      {
                                      		showCountDownDialog();
											mHandler.sendEmptyMessageDelayed(MSG_COUNT_DOWN_1S, 1000);
                                      }
									  else if(msg.what == MSG_COUNT_DOWN_1S)
								      {
								      		if(iCount > 0)
											{
												iCount--;
												localDialog.setMessage(getString(R.string.count_down_hint_head).toString() + " " + iCount + " " + getString(R.string.count_down_hint).toString());
												mHandler.sendEmptyMessageDelayed(MSG_COUNT_DOWN_1S, 1000);
							      			}
											else
											{
												//power off
												localDialog.dismiss();
											if(false)
											{
												long mDownTime = SystemClock.uptimeMillis();  
											    long when = mDownTime;  
  											    final KeyEvent keyPower = new KeyEvent(mDownTime, when, KeyEvent.ACTION_UP, 26, 0,  
           												 0, -1, 0, KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, InputDevice.SOURCE_KEYBOARD);  

												IWindowManager mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));  
//											    try{  
//											        mWindowManager.injectInputEventNoWait(keyPower); 
													
//											    } catch (RemoteException ex) { 
											    
//											    } 
											}
											else
											{
												Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
												intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
												intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
												startActivity(intent);
											/***
												PowerManager powerManager = (PowerManager) CountDownService.this.getSystemService(Context.POWER_SERVICE);
												//powerManager.reboot("recovery");
												powerManager.goToSleep(100000);
												Log.d(TAG, "goToSleep");
											***/
											}
											}
									  }

                                  };
                              };



	@Override
	public void onCreate(){
		super.onCreate();
		Log.d(TAG,"FindService onStart");
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("COM.GOOGLETV.SLEEP.TIMER");
		this.registerReceiver(new SleepTimerBroadcastReciver(), intentFilter);	
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId){
        Log.d(TAG,"FindService onStart");
        super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
        Log.d(TAG,"FindService onDestroy");
		super.onDestroy();
	}
/**	
	@Override

	 public void onAttachedToWindow()

	 { // TODO Auto-generated method stub

	    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

	    super.onAttachedToWindow();

	 }
***/
    private void showCountDownDialog()
    {
		iCount = 60;
    	//try 
			{
				
				AlertDialog.Builder builder = new Builder(CountDownService.this);
				//AlertDialog.Builder builder = new Builder(rContext);
				builder.setTitle(R.string.power_off);
				builder.setMessage(getString(R.string.count_down_hint_head).toString() + " " + iCount + " " + getString(R.string.count_down_hint).toString());
				builder.setCancelable(false);
				builder.setPositiveButton(android.R.string.ok, new OnClickListener(){
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
					intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}});
			builder.setNegativeButton(android.R.string.cancel, new OnClickListener(){
				
				public void onClick(DialogInterface dialog, int which) {
					mHandler.removeMessages(MSG_COUNT_DOWN_1S);
					SharedPreferences mSetsleeptimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
					editor = mSetsleeptimer.edit();               
					String s=String.valueOf(0);
					editor.putString("sleep_timer", s);                  
					editor.commit();
					dialog.dismiss();					
					return ;
				}});

				//builder.setTitle(R.string.hint);
				Log.d(TAG, "before show dialog = ");
				/***
				builder.setPositiveButton(R.string.ok, new OnClickListener() {
					  
					  
				 @Override
				 public void onClick(DialogInterface dialog, int which) {
					   if(which == KeyEvent.KEYCODE_BACK)
						   return;
					  dialog.dismiss();
	    				   mHandler.sendEmptyMessageDelayed(WAIT_COPY_FILE_BEGIN_DIALOG, 50);
					   Log.d(TAG,"cccccccccccccccccccccccccccc6666666688888888888888888888");

					   }
				  });

				  builder.setNegativeButton(R.string.cancle, new OnClickListener() {

				  @Override
				  public void onClick(DialogInterface dialog, int which) {
					   if(which == KeyEvent.KEYCODE_BACK)
						   return;
					   FirstComplete.setFirst(false);
					   isShowDialog = false;
				          dialog.dismiss();
					    Log.d(TAG,"9999999999999999999999999988888888");
				          exitUsbUpdateActivity();
				       }
				  });
				***/
				
				localDialog = builder.create();
				localDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//
				
				localDialog.show();
				
				//isShowDialog = true;
				  
/*				localDialog.setOnKeyListener(new OnKeyListener() {
					     
				    @Override
				    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				      
					    Log.d(TAG, "setOnKeyListener");
					    {
							mHandler.removeMessages(MSG_COUNT_DOWN_1S);
							localDialog.dismiss();
						    return true;
					    }
				    }
			    });
*/				  
			} 
/**
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
***/
    }

	private class SleepTimerBroadcastReciver extends BroadcastReceiver {  
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d(TAG, "&&&&&&&&&&&&&&&&&&&&&&DateTimeSettings.this.sendBroadcast");
			if(action.equals("COM.GOOGLETV.SLEEP.TIMER")) {
				int sleepMode = intent.getIntExtra("SleepTimeMode", 0);
				Log.d(TAG, "&&&&&&&&&&&&&&&&&&&&&&DateTimeSettings.this.sendBroadcast:"+sleepMode);

				switch(sleepMode)
		    	{
					case 0:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						break;
					case 1:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_10MIN);
						break;
					case 2:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_20MIN);
						break;
					case 3:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_30MIN);
						break;
					case 4:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_40MIN);
						break;
					case 5:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_50MIN);
						break;
					case 6:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_60MIN);
						break;
					case 7:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_90MIN);
						break;
					case 8:
						mHandler.removeMessages(MSG_SET_SLEEP_TIMER);
						mHandler.sendEmptyMessageDelayed(MSG_SET_SLEEP_TIMER, SLEEP_TIMER_120MIN);
						break;
					default:
						break;
				}

			}
		}

	}
}
